import * as THREE from "three";
import { MemoryManager } from "fast-three-sketch";
import { Shelf, CargoPoint } from "./Shelf";

let $id = 0;

const material = new THREE.MeshLambertMaterial();

new THREE.TextureLoader().load("./textures/box.png", texture => {
    material.map = texture;
    material.needsUpdate = true;
});

export type CargoDescription = {
    name?: string,
    price?: number,
};


/**
 * 货物 如何构建构造函数
 * 
 * 属性：
 *      price：货物价格
 *      id：货物编号，
 *      name：货物名称
 *      object：货物的3D对象
 *      shelf：货物所属的货架
 *      cargoPoint：货物所属的存放点
 * 
 * 方法：
 *      init：创建货物的3D对象
 *      addToShelf：将货物添加到货架
 *      removeFromShelf：将货物从货架移除
 *      dispose：释放内存资源 
 */
export class Cargo {

    object: THREE.Object3D;
    name: string;
    id: number;
    price: number;

    shelf: Shelf;
    cargoPoint: CargoPoint;

    height: number;

    constructor(name: string, price: number) {

        this.object = new THREE.Object3D();
        this.object.name = name;
        this.name = name;
        this.id = $id++;
        this.price = price;

        this.shelf = undefined;
        this.cargoPoint = undefined;
    }

    /** 创建3D货物对象 */
    init(width: number, height: number, depth: number) {

        const geometry = new THREE.BoxGeometry(width, height, depth);
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.y = height / 2;
        this.object.add(mesh);

        this.height = height;

        this.object.userData.cargo = this;

        mesh.userData.cargo = this;
    }

    /**
     * 将货物添加到货架上 
     * @param shelf 货架
     */
    addToShelf(shelf: Shelf, cargoPoint: CargoPoint = undefined) {
        shelf.addCargo(this, cargoPoint);
    }

    /** 将货物从货架移除 */
    removeFromShelf() {
        if (this.shelf) {
            this.shelf.removeCargo(this);
        }
    }

    dispose() {
        MemoryManager.dispose(this.object, true);
    }
}